﻿<%@ WebHandler Language="C#" Class="ApsPoolHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Text;

//Description:排产池维护处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:longb
//create Date:2023-02-14
public class ApsPoolHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "InitPageData": //获取页面初始化数据
                    InitPageData(context);
                    break;
                case "GetApsPoolData": //查询排产池信息
                    GetApsPoolData(context);
                    break;
                case "SaveApsPoolData": //保存排产池信息
                    SaveApsPoolData(context);
                    break;
                case "DeleteApsPool": //删除排产池信息
                    DeleteApsPool(context);
                    break;
                case "EnableOrStopUseApsPool"://排产池信息--启用/停用
                    EnableOrStopUseApsPool(context);
                    break;
                case "SaveApsPoolTimeData"://保存开始规则
                    SaveApsPoolTimeData(context);
                    break;
                case "SaveInfinitePool"://保存无限排产池 add by zhangrj 20250721
                    SaveInfinitePool(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    #region 方法

    /// <summary>
    /// 保存无限排产池 add by zhangrj 20250721
    /// </summary>
    /// <param name="context"></param>
    private void SaveInfinitePool(HttpContext context)
    {
        uMESProcessResult res = new uMESProcessResult() { Result = true, Message = "保存成功" };
        Dictionary<string, string> paramDic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        if (string.IsNullOrWhiteSpace(paramDic["infiniteCycle"]))
        {
            res.Result = false; res.Message = "未填写无限产期";
            context.Response.Write(JsonConvert.SerializeObject(res));
            return;
        }
        int infiniteCycle;
        if (!int.TryParse(paramDic["infiniteCycle"], out infiniteCycle)) //验证无限产期是不是有效
        {
            res.Result = false; res.Message = "无限产期不是有效的数字";
            context.Response.Write(JsonConvert.SerializeObject(res));
            return;
        }
        StringBuilder sqlBd = new StringBuilder();
        if (string.IsNullOrWhiteSpace(paramDic["apsPoolID"])) //如果ID为空，则添加
        {
            string apsPoolName = string.Format("{0}无限排产池", m_UserInfo.Factory);//排产池名称
            if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM apspool ap WHERE ap.apspoolname = '{0}'", apsPoolName)) != null)
            {
                res.Result = false; res.Message = "已存在本分厂的无限排产池";
                context.Response.Write(JsonConvert.SerializeObject(res));
                return;
            }
            /*插入到排产池*/
            sqlBd.AppendLine(@"INSERT INTO apspool(apspoolid,apspoolname,createdate,createemployeeid,factoryid,isuse,
                           lastchangedate,lastchangeemployeeid,infinitecycle,apspooltype) VALUES(");
            sqlBd.AppendFormat("'{0}',", Guid.NewGuid().ToString());//ID
            sqlBd.AppendFormat("'{0}',", apsPoolName);//排产池名
            sqlBd.AppendLine("sysdate,");//创建日期
            sqlBd.AppendFormat("'{0}',", m_UserInfo.EmployeeID);//创建人
            sqlBd.AppendFormat("'{0}',", m_UserInfo.FactoryID);//分厂
            sqlBd.AppendLine("0,");//默认有效
            sqlBd.AppendLine("sysdate,");//最近更改日期
            sqlBd.AppendFormat("'{0}',", m_UserInfo.EmployeeID);//最近更改人
            sqlBd.AppendFormat("{0},", infiniteCycle);//无限产期
            sqlBd.AppendLine("2)");//表示本数据为无限排产池
        }
        else
        {
            if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM apspool ap WHERE ap.apspoolid = '{0}' AND ap.apspooltype = '2'", paramDic["apsPoolID"])) == null)
            {
                res.Result = false; res.Message = "选择的排产池不是无限排产池";
                context.Response.Write(JsonConvert.SerializeObject(res));
                return;
            }
            /*更新排产池*/
            sqlBd.AppendLine(@"UPDATE apspool ap SET ");
            sqlBd.AppendFormat("ap.infinitecycle = {0},", infiniteCycle);//无限产期
            sqlBd.AppendLine("ap.lastchangedate = sysdate,");//最新修改日期
            sqlBd.AppendFormat("ap.lastchangeemployeeid = '{0}'", m_UserInfo.EmployeeID);//最新修改人
            sqlBd.AppendFormat(" WHERE ap.apspoolid = '{0}'", paramDic["apsPoolID"]);//主键ID
        }
        DatabaseHelper.ExecuteSql(sqlBd.ToString());
        context.Response.Write(JsonConvert.SerializeObject(res));
    }

    /// <summary>
    /// 获取页面初始化数据
    /// </summary>
    /// <param name="context"></param>
    public void InitPageData(HttpContext context)
    {
        string type = context.Request["type"].ToString();
        string eids = context.Request["eids"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        DataSet set = new DataSet();
        DataTable dt = commonBusiness.GetFactory(new Dictionary<string, string>());
        var wcSQL = @"SELECT WC.WORKCENTERNAME, WC.WORKCENTERID FROM WORKCENTER WC
                    WHERE WC.FACTORYID = '{0}' AND (notes is null or notes <>'已注销')
                    AND not exists ( SELECT aw.WORKCENTERID FROM ApsPool ap LEFT JOIN ApsPoolWorkcenter aw ON aw.APSPOOLID=ap.APSPOOLID WHERE ap.isuse=0 and aw.workcenterid=wc.workcenterid)
                    ";
        if (!string.IsNullOrWhiteSpace(type))//编辑状态，把已维护工区加上
        {
            wcSQL += @" UNION SELECT WC.WORKCENTERNAME, WC.WORKCENTERID FROM WORKCENTER WC where wc.workcenterid in('" + context.Request["type"].ToString().Replace(",", "','") + "')";
        }
        var wcdt = DatabaseHelper.Query_ReturnDatTable(string.Format(wcSQL, m_UserInfo.FactoryID));
        var sql = @"select e.fullname,e.employeename,e.employeeid,s.FACTORYID from roledef ro 
                    left JOIN employeerole erl ON erl.roleid=ro.roleid
                    left JOIN employee e on e.employeeid=erl.employeeid
                    LEFT JOIN SESSIONVALUES s ON s.EMPLOYEEID =e.EMPLOYEEID 
                    where ro.rolename like '%计划员%' AND s.FACTORYID ='{0}'
                    --AND not exists ( SELECT aw.EMPLOYEEID FROM ApsPool ap LEFT JOIN ApsPoolJHYEmp aw ON aw.APSPOOLID=ap.APSPOOLID WHERE ap.isuse=0 and aw.EMPLOYEEID=e.employeeid)";
        if (!string.IsNullOrWhiteSpace(eids))
        {
            sql += " union select e.fullname,e.employeename,e.employeeid,'{0}' FACTORYID from employee e where e.employeeid in ('" + eids.Replace(",", "','") + "')";
        }
        var employeeDT = DatabaseHelper.Query_ReturnDatTable(string.Format(sql, m_UserInfo.FactoryID));
        set.Tables.Add(wcdt);
        set.Tables.Add(employeeDT);
        result.DBTable = dt;
        result.DBDataSet = set;
        result.ReturnData = m_UserInfo;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 查询排产池信息
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPoolData(HttpContext context)
    {
        DataTable data = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        uMESProcessResult result = new uMESProcessResult();
        var selectSQl = @"SELECT NVL(s.apspooltype, '1') apspooltype,s.InfiniteCycle,s.apsrule,s.APSPOOLID,APSPOOLNAME,to_char(CREATEDATE,'yyyy-MM-dd hh24:mi:ss') CREATEDATE,ISUSE,to_char(LASTCHANGEDATE,'yyyy-MM-dd hh24:mi:ss') LASTCHANGEDATE,OFFICIALCYCLE,TRYCYCLE
                        ,e.FULLNAME CREATEEMPLOYEE,e3.FULLNAME LASTCHANGEEMPLOYEE,f.FACTORYNAME,jh.employeename,jh.employeeids,aw.WORKCENTER,aw.WORKCENTERIDS,ap.PRIORITYNAME,'' PriorityList 
                        ,TIMERULENAME,TRSEQUENCE,TIMERULES,ADDTIMES
                        FROM ApsPool s
                        LEFT JOIN FACTORY f ON f.FACTORYID =s.FACTORYID
                        LEFT JOIN EMPLOYEE e ON e.EMPLOYEEID =s.CREATEEMPLOYEEID
                        LEFT JOIN EMPLOYEE e3 ON e3.EMPLOYEEID =s.LASTCHANGEEMPLOYEEID
                        LEFT JOIN (
	                        SELECT wm_concat(e2.fullname) employeename,wm_concat(jh.employeeid) employeeids,jh.APSPOOLID FROM ApsPoolJHYEmp jh 
	                        LEFT JOIN EMPLOYEE e2 ON e2.employeeid=jh.employeeid
	                        GROUP BY jh.APSPOOLID
	                        ) jh ON jh.APSPOOLID=s.APSPOOLID
                        LEFT JOIN (
	                        SELECT wm_concat(w.WORKCENTERNAME) WORKCENTER,wm_concat(aw.WORKCENTERID) WORKCENTERIDS,aw.APSPOOLID FROM ApsPoolWorkcenter aw 
	                        LEFT JOIN WORKCENTER w ON w.WORKCENTERID =aw.WORKCENTERID
	                        GROUP BY aw.APSPOOLID
                        ) aw ON aw.APSPOOLID=s.APSPOOLID
                        LEFT JOIN (
	                        SELECT LISTAGG(ap.PRIORITYNAME,' > ') WITHIN GROUP(ORDER BY SEQUENCE) PRIORITYNAME,ap.APSPOOLID FROM ApsPoolPriority ap GROUP BY ap.APSPOOLID 
                        ) ap ON ap.APSPOOLID=s.APSPOOLID 
                        LEFT JOIN (
	                         SELECT LISTAGG(tr.TIMERULENAME,' > ') WITHIN GROUP(ORDER BY SEQUENCE) TIMERULENAME,
	                         LISTAGG(tr.SEQUENCE,',') WITHIN GROUP(ORDER BY SEQUENCE) TRSEQUENCE,
                             LISTAGG(tr.TIMERULE,',') WITHIN GROUP(ORDER BY SEQUENCE) TIMERULES,
                             LISTAGG(tr.ADDTIME,',') WITHIN GROUP(ORDER BY SEQUENCE) ADDTIMES,
	                        tr.APSPOOLID FROM ApsPoolTimeRule tr GROUP BY tr.APSPOOLID 
                        ) tr ON tr.APSPOOLID=s.APSPOOLID 
                        where 1=1 ";
        if (!string.IsNullOrWhiteSpace(data.Rows[0]["Factory"].ToString())) { selectSQl += "AND s.FactoryID='" + data.Rows[0]["Factory"].ToString() + "'"; }
        if (!string.IsNullOrWhiteSpace(data.Rows[0]["Employee"].ToString())) { selectSQl += "AND jh.employeename like '%" + data.Rows[0]["Employee"].ToString() + "%'"; }
        if (!string.IsNullOrWhiteSpace(data.Rows[0]["IsUse"].ToString())) { selectSQl += "AND s.IsUse='" + data.Rows[0]["IsUse"].ToString() + "'"; }
        if (!string.IsNullOrWhiteSpace(data.Rows[0]["Priority"].ToString()))
        {
            var Priority = string.Empty;
            Priority += "AND (";
            foreach (var p in data.Rows[0]["Priority"].ToString().Split(','))
            {
                Priority += " ap.PRIORITYCODE like '%" + p + "%' or";
            }
            selectSQl += Priority.TrimEnd('r').TrimEnd('o') + ")";
        }
        var paraPage = new uMESPagingDataDTO();
        paraPage.CurrentPageIndex = Convert.ToInt32(pageNumber);
        paraPage.PageSize = Convert.ToInt32(pageSize);
        paraPage.strSQL = selectSQl;
        result = DatabaseHelper.RunProcedureForPage(paraPage);
        foreach (DataRow row in result.DBTable.Rows)
        {
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(string.Format("SELECT * FROM ApsPoolPriority where APSPOOLID='" + row["APSPOOLID"] + "'"));
            row["PriorityList"] = JsonConvert.SerializeObject(dt);
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 保存排产池信息
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPoolData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable data = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        DataTable Prioritys = JsonConvert.DeserializeObject<DataTable>(context.Request["Prioritys"].ToString());
        DataTable ApsPoolNameDT = DatabaseHelper.Query_ReturnDatTable(string.Format("select * from ApsPool where ApsPoolName='" + data.Rows[0]["APSPOOLNAME"] + "'"));
        if (string.IsNullOrWhiteSpace(data.Rows[0]["APSPOOLID"].ToString()) && ApsPoolNameDT.Rows.Count > 0)
        {
            result.Message = "排产池已存在，禁止操作";
            result.ReturnData = true;
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        var ApsPoolID = string.IsNullOrWhiteSpace(data.Rows[0]["APSPOOLID"].ToString()) ? Guid.NewGuid().ToString() : data.Rows[0]["APSPOOLID"].ToString();
        ArrayList SqlArr = new ArrayList();
        if (string.IsNullOrWhiteSpace(data.Rows[0]["APSPOOLID"].ToString()))
        {
            var insertSQL = @"insert into ApsPool(ApsPoolID,ApsPoolName,FactoryID,IsUse,TryCycle,OfficialCycle,CreateEmployeeid,CreateDate,apsrule,apspooltype) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}',sysdate,'{7}','1')";
            SqlArr.Add(string.Format(insertSQL, ApsPoolID, data.Rows[0]["APSPOOLNAME"], m_UserInfo.FactoryID, string.IsNullOrWhiteSpace(data.Rows[0]["ISUSE"].ToString()) ? "0" : data.Rows[0]["ISUSE"].ToString(), data.Rows[0]["TRYCYCLE"], data.Rows[0]["OFFICIALCYCLE"], m_UserInfo.EmployeeID, data.Rows[0]["APSRULE"]));
        }
        else
        {
            SqlArr.Add(string.Format("update ApsPool set ApsPoolName='{0}',IsUse='{1}',TryCycle='{2}',OfficialCycle='{3}',LastChangeEmployeeId='{4}',apsrule='{6}',LastChangeDate=sysdate where ApsPoolID='{5}'", data.Rows[0]["APSPOOLNAME"], data.Rows[0]["ISUSE"], data.Rows[0]["TRYCYCLE"], data.Rows[0]["OFFICIALCYCLE"], m_UserInfo.EmployeeID, ApsPoolID, data.Rows[0]["APSRULE"]));
        }
        SqlArr.Add(string.Format("delete from ApsPoolJHYEmp where ApsPoolID='{0}'", ApsPoolID));
        foreach (var eID in data.Rows[0]["employee"].ToString().Split(','))
        {
            SqlArr.Add(string.Format("INSERT INTO ApsPoolJHYEmp(APSPOOLID,EMPLOYEEID) VALUES('{0}','{1}')", ApsPoolID, eID));
        }
        SqlArr.Add(string.Format("delete from ApsPoolWorkcenter where ApsPoolID='{0}'", ApsPoolID));
        foreach (var eID in data.Rows[0]["workcenter"].ToString().Split(','))
        {
            SqlArr.Add(string.Format("INSERT INTO ApsPoolWorkcenter(APSPOOLID,WorkcenterID) VALUES('{0}','{1}')", ApsPoolID, eID));
        }
        SqlArr.Add(string.Format("delete from ApsPoolPriority where ApsPoolID='{0}'", ApsPoolID));
        foreach (DataRow row in Prioritys.Rows)
        {
            SqlArr.Add(string.Format("INSERT INTO ApsPoolPriority(APSPOOLID,PriorityCode,PriorityName,Sequence) VALUES('{0}','{1}','{2}','{3}')", ApsPoolID, row["PriorityCode"], row["PriorityName"], row["Sequence"]));
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(SqlArr);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 删除排产池信息
    /// </summary>
    /// <param name="context"></param>
    public void DeleteApsPool(HttpContext context)
    {
        DataTable data = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        ArrayList SqlArr = new ArrayList();
        foreach (DataRow row in data.Rows)
        {
            if (row["isuse"].ToString() == "1")
            {
                SqlArr.Add(string.Format("delete from ApsPool where APSPOOLID='{0}'", row["APSPOOLID"]));
                SqlArr.Add(string.Format("delete from ApsPoolJHYEmp where APSPOOLID='{0}'", row["APSPOOLID"]));
                SqlArr.Add(string.Format("delete from ApsPoolWorkcenter where APSPOOLID='{0}'", row["APSPOOLID"]));
                SqlArr.Add(string.Format("delete from ApsPoolPriority where APSPOOLID='{0}'", row["APSPOOLID"]));
                SqlArr.Add(string.Format("delete from ApsPoolTimeRule where APSPOOLID='{0}'", row["APSPOOLID"]));
            }
        }
        uMESProcessResult result = new uMESProcessResult();
        if (SqlArr.Count > 0)
        {
            result.Result = DatabaseHelper.ExecuteSqlListTran(SqlArr);
            result.Message = result.Result ? "删除成功" : "删除失败";//+ SqlArr.Count + "条记录" + (data.Rows.Count != SqlArr.Count ? ",删除失败" + data.Rows.Count + "条启用记录" : "")
        }
        else
        {
            result.Message = "请选择停用记录，再进行操作";
        }

        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 排产池信息--启用/停用
    /// </summary>
    /// <param name="context"></param>
    public void EnableOrStopUseApsPool(HttpContext context)
    {
        DataTable data = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        ArrayList SqlArr = new ArrayList();
        foreach (DataRow row in data.Rows)
        {
            SqlArr.Add(string.Format("update ApsPool set isuse='{0}' where APSPOOLID='{1}'", row["isuse"].ToString() == "0" ? 1 : 0, row["APSPOOLID"]));
        }
        uMESProcessResult result = new uMESProcessResult();
        result.Result = DatabaseHelper.ExecuteSqlListTran(SqlArr);
        result.Message = result.Result ? "修改成功" : "修改失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 保存开始规则
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPoolTimeData(HttpContext context)
    {
        DataTable data = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var ApsPoolID = context.Request["ApsPoolID"].ToString();
        ArrayList SqlArr = new ArrayList();
        if (data.Rows.Count > 0)
        {
            SqlArr.Add(string.Format("delete from ApsPoolTimeRule where APSPOOLID='{0}'", ApsPoolID));
            foreach (DataRow row in data.Rows)
            {
                var trSQL = @"insert into ApsPoolTimeRule(APSPOOLID,TIMERULE,TIMERULENAME,SEQUENCE,ADDTIME) VALUES('{0}','{1}','{2}','{3}','{4}')";
                SqlArr.Add(string.Format(trSQL, ApsPoolID, row["PRIORITYCODE"], row["PRIORITYNAME"], row["SEQUENCE"], row["H"]));
            }
        }
        uMESProcessResult result = new uMESProcessResult();
        result.Result = DatabaseHelper.ExecuteSqlListTran(SqlArr);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    #endregion
}